package com.godenwater.recv.decode;

import org.apache.mina.core.buffer.IoBuffer;

import cn.gov.mwr.sl651.utils.ByteUtil;

import com.godenwater.recv.model.CommonMessage;

public class Szy206MessageDecoder {

	public static CommonMessage decode(IoBuffer buffer) {

		cn.gov.mwr.szy206.SzyMessageHeader header = new cn.gov.mwr.szy206.SzyMessageHeader();

		header.setStartBit(new byte[] { cn.gov.mwr.szy206.SzySymbol.STX });
		// 报文长度
		byte[] bodySize = new byte[header.getBodySizeLen()];
		buffer.get(bodySize);
		header.setBodySize(bodySize);

		// 报文开始符
		byte[] bodyStartBit = new byte[header.getBodyStartBitLen()];
		buffer.get(bodyStartBit);
		header.setBodyStartBit(bodyStartBit);

		// 转换报文中的上下行标识及报文长度
		int bodySizeLen = ByteUtil.bytesToUbyte(bodySize);// 报文长度计算

		int crclen = 1;

		// --------------------------------
		CommonMessage message = new CommonMessage();
		message.setHeader(header);
		message.setCrclen(crclen);
		message.setBodySize(bodySizeLen);

		return message;
	}

	public static CommonMessage decode(byte[] buffer) {

		cn.gov.mwr.szy206.SzyMessageHeader header = new cn.gov.mwr.szy206.SzyMessageHeader();

		header.setStartBit(new byte[] { cn.gov.mwr.szy206.SzySymbol.STX });

		int pos = 1;
		// 报文长度
		byte[] bodySize = new byte[header.getBodySizeLen()];
		System.arraycopy(buffer, pos, bodySize, 0, bodySize.length);
		pos = pos + header.getBodySizeLen();
		header.setBodySize(bodySize);

		// 报文开始符
		byte[] bodyStartBit = new byte[header.getBodyStartBitLen()];
		System.arraycopy(buffer, pos, bodyStartBit, 0, bodyStartBit.length);
		pos = pos + header.getBodyStartBitLen();
		header.setBodyStartBit(bodyStartBit);

		// 转换报文中的上下行标识及报文长度
		int bodySizeLen = ByteUtil.bytesToUbyte(bodySize);// 报文长度计算
		byte[] bodyContent = new byte[bodySizeLen];// 根据前面header的内容来获取长度
		System.arraycopy(buffer, pos, bodyContent, 0, bodyContent.length);
		pos = pos + bodySizeLen;

		// 终止符
		byte[] eof = new byte[1];
		System.arraycopy(buffer, pos, eof, 0, eof.length);
		pos = pos + eof.length;
		// 校验码
		int crclen = 1;
		byte[] crc = new byte[crclen];
		System.arraycopy(buffer, pos, crc, 0, crc.length);
		pos = pos + crc.length;
		// --------------------------------
		CommonMessage message = new CommonMessage();
		message.setHeader(header);
		message.setCrclen(crclen);
		message.setBodySize(bodySizeLen);
		message.setContents(bodyContent);
		message.setEOF(eof[0]);
		message.setCRC(crc);

		return message;
	}

}
